/**
 *
 */
package com.ybkj.daijia.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.config.WeixinApi;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.DriverRebateMapper;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverRebate;
import com.ybkj.daijia.server.service.DriverRebateService;
import com.ybkj.daijia.server.utils.SslUtil;
import java.net.URL;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @author Shine
 * 该功能需要主动联系 wx服务器,所以要求config,properties 配置正确
 */
@Service
public class DefaultDriverRebateService implements DriverRebateService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    WeixinApi weixinApi;
    @Autowired
    private DriverRebateMapper driverRebateMapper;
    @Autowired
    private DriverMapper driverMapper;

    @Transactional(rollbackFor = Exception.class)
    public DriverRebate save(DriverRebate driverRebate) {

        driverRebateMapper.insertRecord(driverRebate);

        return driverRebate;

    }

    @Transactional(rollbackFor = Exception.class)
    public void update(DriverRebate driverRebate) {

        driverRebateMapper.updateByPrimaryKey(driverRebate);

    }

    @Override
    public DriverRebate findOne(Long driverId) {
        return driverRebateMapper.selectByPrimaryKey(driverId);
    }

    @Override
    public List<DriverRebate> findAll() {
        return driverRebateMapper.selectAll();
    }

    @Override
    public DriverRebate findByDriverId(Long driverId) {
        return driverRebateMapper.selectByDriverId(driverId);
    }

    @Override
    public String getWeixinShareCodeUrl(Driver driver) {
        String wxRebateQrCodeUrl = driver.getWxRebateQrCodeUrl();
        if (null != wxRebateQrCodeUrl && 0 != wxRebateQrCodeUrl.trim().length()) {
            return wxRebateQrCodeUrl;
        }
        try {
            String url = weixinApi.getWeixinBaseUrl() + WeixinApi.GET_DRIVER_WEIXIN_SHARE_URL;
            URL urlPost = null;
            urlPost = new URL(url);
            if ("https".equalsIgnoreCase(urlPost.getProtocol())) {//判定网址是否信任，不信任则调用忽略信任工具类SslUtil
                SslUtil.ignoreSsl();
            }
            String jsonStr = restTemplate
                .getForObject(url, String.class, driver.getId() + "and" + driver.getName());
            JSONObject re = JSONObject.parseObject(jsonStr);
            if (re.getBoolean("success")) {
                wxRebateQrCodeUrl = re.getString("url");
                driverMapper.updateWxRebateQrCodeUrl(wxRebateQrCodeUrl, driver.getId());
                return wxRebateQrCodeUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}